import { createStore } from 'vuex'
import { getPhone, register, login } from '@/utils/api'

let lifeData = {};

try {
	// 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
	lifeData = uni.getStorageSync('lifeData');
} catch(e) {
	console.log(e)
}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = [
	'vx_uid',// 用户id
	'vx_token',
	'vx_role',
	'vx_sessionKey',
	'vx_openId',

	//  -----------------------------
	'vx_tokenType',
	'vx_isSendVerifiCode', // 是否发送了验证码
	'vx_verifiCodeCountdown', // 验证码倒计时
	'vx_usrInfo',//用户信息
	'vx_city',//城市
	'vx_city_id',//城市选择
	'vx_u_info',
	'vx_gps',//gps
	'hbid',//
	'pwdStatus', 
];

const store = createStore({
	// 下面这些值仅为示例，使用过程中请删除
	state: {
		// 如果上面从本地获取的lifeData对象下有对应的属性，就赋值给state中对应的变量
		vx_uid:						lifeData.vx_uid || '',//用户id
	 	vx_token:                   lifeData.vx_token || '',

		vx_city:					lifeData.vx_city || '',
		vx_city_id:					lifeData.vx_city_id || '',
		vx_u_info:					lifeData.vx_u_info || {role: '0'},
		vx_openId:					lifeData.vx_openId || '',
		vx_role_:					lifeData.vx_role || '0',
		vx_sessionKey:				lifeData.vx_sessionKey || '',
		vx_usrInfo:					lifeData.vx_usrInfo || {},

        vx_phone_code:'',
		vx_phone:'',
		vx_sex:'',
		name:'',
	},
	mutations: {
		
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if(nameArr.length >= 2) {
				let obj = state[nameArr[0]];
				for(let i = 1; i < len - 1; i ++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveLifeData(saveKey, state[saveKey])
		}
	},
	actions: {
		$dLogin({ commit, state }, code) {
			return new Promise(async (resolve, reject) => {
				const res = await login({ token:null,body:{code:code} })
				if (res.code === 101) {
					commit('$uStore', { name: 'vx_sessionKey', value: res.Data.session_key })
					commit('$uStore', { name: 'vx_openId', value: res.Data.openid })
					resolve({ type: false })
				} else if (res.code === 200) {
					commit('$uStore', { name: 'vx_u_info', value: res.Data })
					commit('$uStore', { name: 'vx_token', value: res.Data.Token })
					commit('$uStore', { name: 'vx_uid', value: res.Data.Id })
					// commit('$uStore', { name: 'vx_role', value: res.Data.role })
					commit('$uStore', { name: 'vx_openId', value: res.Data.OpenId })
					resolve({ type: true, payload: res.Data })
				}
			})
		},
		async $dGetPhone({ commit, state }, payload) {
			return new Promise(async (resolve, reject) => {
				const phoneRes = await getPhone({
					SessionKey: state.vx_sessionKey,
					encryptedData: payload.encryptedData,
					iv: payload.iv
				})
				if (phoneRes.Data.phoneNumber) {
					let data = {
						OpenId: state.vx_openId,
						Phone: phoneRes.Data.phoneNumber,
						Lat: '',
						Lon: '',
						Province: '',
						City: '',
						County: '',
						Address: '',
						Account: 'LoginUser',
						Key: '65E47265-40E0-4C98-8E9A-04886E5C410C',
					}
					resolve({ ...data })
				}
			})
		},
		async $dRegister({ commit, state }, payload) {
			return new Promise(async (resolve, reject) => {
				const res = await register(payload)
				const { Code, Data } = res
				if (Code === 200) {
					commit('$uStore', { name: 'vx_u_info', value: Data })
					commit('$uStore', { name: 'vx_token', value: Data.Token })
					commit('$uStore', { name: 'vx_uid', value: Data.Id })
					// commit('$uStore', { name: 'vx_role', value: Data.role })
					// if (state.hbid) {
					// 	commit('$uStore', { name: 'hbid', value: '' })
					// }
					resolve({ type: true, payload: Data })
				} else {
					resolve({ type: false, payload: res.Message })
				}
			})
		}
	}
})

// 保存变量到本地存储中
const saveLifeData = function(key, value) {
	// 判断变量名是否在需要存储的数组中
	if (saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = uni.getStorageSync('lifeData');
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		uni.setStorageSync('lifeData', tmp);
	}
}

export default store
